package com.base.data.tools;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.Environment;

import androidx.annotation.NonNull;

import com.base.common.utils.UIUtils;
import com.base.data.R;
import com.orm.helper.ManifestHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

public class DatabaseUtil {


    /**
     * 将assets中的db文件拷贝到databases中
     */
    @SuppressLint("SdCardPath")
    public static void packDataBase(@NonNull Context context, @NonNull String assetsAddress) {
        // com.kinth.youdian 是程序的包名，请根据自己的程序调整
        // /data/data/com.kinth.youdian/databases目录是准备放 SQLite 数据库的地方，也是 Android 程序默认的数据库存储目录

        String DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        // 获取 Manifest中 数据库的名字 xxx.db
        String DB_NAME = UIUtils.getApplicationMetaData(context, ManifestHelper.METADATA_DATABASE);


        // 检查 SQLite 数据库文件是否存在
        if (!(new File(DB_PATH + DB_NAME)).exists()) {
            // 如 SQLite 数据库文件不存在，再检查一下 database 目录是否存在
            File f = new File(DB_PATH);
            // 如 database 目录不存在，新建该目录
            if (!f.exists()) {
                f.mkdir();
            }

            try {
                // 得到 assets 目录下我们实现准备好的 SQLite 数据库作为输入流
                InputStream is = context.getAssets().open(assetsAddress);
                // 输出流,在指定路径下生成db文件
                OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);

                // 文件写入
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }

                //强制写入文件
                os.flush();
                // 关闭文件流
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * 备份
     *
     * @param backupDBPath 备份的绝对路径 包括文件名
     */
    public static String backUpDB(Context mContext, String backupDBPath) {
        String err = "";
        try {

            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {

                // 获取 Manifest中 数据库的名字 xxx.db
                String DB_NAME = UIUtils.getApplicationMetaData(mContext, ManifestHelper.METADATA_DATABASE);
                String currentDBPath = "//data/" + mContext.getPackageName() + "/databases/" + DB_NAME;

                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(backupDBPath);

                if (currentDB.exists()) {
                    if (backupDB.exists()) {
                        backupDB.delete();
                    }
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();

                    MediaScannerConnection.scanFile(UIUtils.getContext(), new String[]{backupDB.getAbsolutePath()}, null, null);
                }
            } else {
                err = mContext.getResources().getString(R.string.sd_not_write_permission);
            }


        } catch (Exception e) {
            err = e.getMessage();
        }
        return err;
    }


    /**
     * 还原
     */

    public static String restoreDB(Context mContext, String backupDBPath) {

        try {
            File sd = Environment.getExternalStorageDirectory();

            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                // 获取 Manifest中 数据库的名字 xxx.db
                String DB_NAME =  UIUtils.getApplicationMetaData(mContext, ManifestHelper.METADATA_DATABASE);

                String currentDBPath = "//data/" + mContext.getPackageName() + "/databases/" + DB_NAME;


                File currentDB = new File(data, currentDBPath);

                File backupDB = new File(backupDBPath);

                if (!backupDB.exists()) {
                    return "文件不存在";
                }


                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(backupDB).getChannel();
                    FileChannel dst = new FileOutputStream(currentDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();

                } else {

                    // 得到  目录下我们实现准备好的 SQLite 数据库作为输入流
                    InputStream is = new FileInputStream(backupDB);
                    // 输出流,在指定路径下生成db文件
                    OutputStream os = new FileOutputStream(currentDBPath);

                    // 文件写入
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = is.read(buffer)) > 0) {
                        os.write(buffer, 0, length);
                    }

                    // 关闭文件流
                    os.flush();
                    os.close();
                    is.close();

                }
            } else {
                return mContext.getResources().getString(R.string.sd_not_write_permission);
            }


        } catch (Exception e) {
            return e.getMessage();
        }

        return "";
    }


}
